package com.example.mycommunity.provider;

import com.example.mycommunity.exception.CustomizeErrorCode;
import com.example.mycommunity.exception.CustomizeException;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Service
public class TecentProvider {

    @Value("${tecent.cloud.publicKey}")
    private String publicKey;

    @Value("${tecent.cloud.privateKey}")
    private String privateKey;

    @Value("${tecent.cloud.appId}")
    private String appId;

    @Value("${tecent.cloud.bucketName}")
    private String bucketName;

    @Value("${tecent.cloud.expires}")
    private Long expires;








    // 创建bucket
    public void CreateBucketDemo() {
        // 1 初始化用户身份信息(appid, secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(publicKey, privateKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket名称, 需包含appid
//        String bucketName = "publicreadbucket-" + appId;

        CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
        // 设置bucket的权限为PublicRead(公有读私有写), 其他可选有私有读写, 公有读私有写
        createBucketRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        Bucket bucket = cosclient.createBucket(createBucketRequest);

        // 关闭客户端
        cosclient.shutdown();
    }


    // 删除bucket, 只用于空bucket, 含有数据的bucket需要在删除前清空删除。
    public  void DeleteBucketDemo() {
        // 1 初始化用户身份信息(appid, secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(publicKey, privateKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);
        // bucket名称, 需包含appid
//        String bucketName = "publicreadbucket-" + appId;
        // 删除bucket
        cosclient.deleteBucket(bucketName);

        // 关闭客户端
        cosclient.shutdown();
    }


    // 查询bucket是否存在
    public void JudgeBucketExistDemo() {
        // 1 初始化用户身份信息(appid, secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(publicKey, privateKey);
        // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
        // 3 生成cos客户端
        COSClient cosclient = new COSClient(cred, clientConfig);

//        String bucketName = "publicreadbucket-" + appId;
        // 判断bucket是否存在
        boolean flag = cosclient.doesBucketExist(bucketName);

        // 关闭客户端
        cosclient.shutdown();
    }


    public String upload(InputStream fileStream, String mimeType, String fileName) {
        String generatedFileName;
        String[] filePaths = fileName.split("\\.");
        if(filePaths.length > 1){
            generatedFileName = UUID.randomUUID().toString() + "." + filePaths[filePaths.length - 1];
        }else{
            return null;
        }

        try{
            COSCredentials cred = new BasicCOSCredentials(publicKey, privateKey);
            // 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
            // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
            Region region = new Region("ap-shanghai");
            ClientConfig clientConfig = new ClientConfig(region);
            // 3 生成 cos 客户端。
            COSClient cosClient = new COSClient(cred, clientConfig);

            // 图片上传
//            String key = "exampleObject1." + filePaths[filePaths.length - 1];
            File file = new File("1.txt");
            copyInputStreamToFile(fileStream, file);

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, generatedFileName, file);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

//            System.out.println(putObjectResult);
            if(putObjectResult != null){
                // 返回一个带签名的下载链接
                String url;
                GeneratePresignedUrlRequest req =
                        new GeneratePresignedUrlRequest(bucketName, generatedFileName, HttpMethodName.GET);
                Date expirationDate = new Date(System.currentTimeMillis() + expires);
                req.setExpiration(expirationDate);
                URL temp = cosClient.generatePresignedUrl(req);
                url = temp.toString();
                cosClient.shutdown();
                return url;
            }else{
                throw new CustomizeException(CustomizeErrorCode.FILE_UPLOAD_FAIL);
            }


        }catch (Exception e){
            e.printStackTrace();
            throw new CustomizeException(CustomizeErrorCode.FILE_UPLOAD_FAIL);
        }


    }
    private void copyInputStreamToFile(InputStream inputStream, File file)
            throws IOException {
        try (FileOutputStream outputStream = new FileOutputStream(file)) {
            int read;
            byte[] bytes = new byte[1024];
            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }

        }

    }


}
